package services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import repositories.ParticipantRepository;
import security.Authority;
import security.LoginService;
import security.UserAccount;
import domain.Participant;

@Service
@Transactional
public class ParticipantService {

	//Managed repository
	@Autowired
	ParticipantRepository participantRepository;

	//Supporting services
	
	//Constructors
	public ParticipantService() {
		super();
	}

	//Simple CRUD methods
	
	public Participant create() {
		
		Participant participant = new Participant();
		
		Authority auth = new Authority();
		auth.setAuthority("PARTICIPANT");
		
		UserAccount userAccount = new UserAccount();
		userAccount.addAuthority(auth);
		
		participant.setUserAccount(userAccount);

		return participant;
	}

	public void save(Participant participant) {
		
		Assert.notNull(participant);
		participantRepository.save(participant);
	}

	
	//Other bussiness methods
	public Participant findByPrincipal() {
		Participant result;
		UserAccount userAccount;
		userAccount = LoginService.getPrincipal();
		Assert.notNull(userAccount);
		result = findByUserAccount(userAccount);
		Assert.notNull(result);
		return result;
	}

	public Participant findByUserAccount(UserAccount userAccount) {
		Assert.notNull(userAccount);
		Participant result;
		result = participantRepository.findByUserAccountId(userAccount.getId());

		return result;
	}
}
